<template>
  <div class="body Abnormal">
    <header><i class="iconfont icon-xiangzuo1" @click="goPrev"></i><span>异常上报</span></header>
    <div class="kong"></div>
    <div class="common-box">
      <div v-if='!omsNo' class="content-box">
        <v-scan @scanData="scanData" :switchScan="switchScan"></v-scan>
      </div>
    </div>
    <div class="form-content">
      <div class="form-item">
        <label>母单号 <span style="color:red">*</span></label>
        <el-input class="form-input" type="text" v-model="OMS.omsNo" :disabled="true"></el-input>
      </div>
      <div class="form-item">
        <label>异常类型 <span style="color:red">*</span></label><br>
        <el-select v-model="aboType" placeholder="异常类型选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.abnormalType"
            :label="item.abnormalType"
            :value="item.abnormalType">
          </el-option>
        </el-select>
      </div>
      <div class="form-item">
        <label>异常原因 <span style="color:red">*</span></label><br>
        <el-select v-model="aboReason" placeholder="异常原因选择">
          <el-option
            v-for="item in reasonOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div v-if="(linkno=='30' || linkno=='40') && aboType == '客户类' && aboReason == '经客户同意，更改收派时间'" class="form-item">
				<label>改派预约日期 <span style="color:red">*</span></label><br>
          <el-date-picker
          v-model="reassignmentAppointmentTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择改派预约日期"
          :picker-options="pickerOptions1">
        </el-date-picker>
			</div>
      <div v-if="(linkno=='30' || linkno=='40') && aboType == '客户类' && aboReason == '经客户同意，更改收派时间'" class="form-item">
				<label>改派预约时间段 <span style="color:red">*</span></label><br>
				<el-select v-model="appointmentPeriod" placeholder="选择改派预约时间段">
					<el-option v-for="item in appointmentPeriodList" :key="item.id" :label="item.name" :value="item.name">
					</el-option>
				</el-select>
			</div>
			<div v-if="(linkno=='30' || linkno=='40') && aboType == '客户类' && aboReason == '经客户同意，更改收派时间'" class="form-item">
				<label>改派联系人 <span style="color:red">*</span></label><br>
				<el-select v-model="reassignRecipientContact" placeholder="改派联系人选择">
					<el-option v-for="item in recipientContactList" :key="item" :label="item" :value="item">
					</el-option>
				</el-select>
			</div>
			<div v-if='(linkno=="30" || linkno=="40") && aboType=="客户类" && (aboReason == "寄方客户要求退回" || aboReason == "客户要求转寄其它地址") && projectType == 1' style="color:red">您所提交异常的此票订单（含所有子母单）都将退运或转寄，如有疑问请与客服沟通清楚后再提交此类异常！</div>
      <div class="form-item">
        <label>异常描述</label>
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入内容"
          v-model="aboText">
        </el-input>
      </div>
			<div class="form-item" v-if='(linkno=="30" || linkno=="40") && aboType=="客户类" && (aboReason == "寄方客户要求退回" || aboReason == "客户要求转寄其它地址") && projectType == 1'>
				<label> 网点人员工号 <span style="color:red">*</span></label>
				<div class="sf-network-num">
					<el-input class="form-input" type="text" v-model="sfNetworkNum" placeholder="请扫描/输入交接 网点人员工号"></el-input>
                    <i class="iconfont icon-sousuoxiawu-" @click="ScanSFNumber('sfNetworkNum')"></i>
					<span @click="queryNetCode">查网点</span>
				</div>
			</div>
			<div class="form-item" v-if='(linkno=="30" || linkno=="40") && aboType=="客户类" && (aboReason == "寄方客户要求退回" || aboReason == "客户要求转寄其它地址") && projectType == 1'>
				<label> 网点代码 <span style="color:red">*</span></label>
				<el-input class="form-input" type="text" v-model="sfNetCode" placeholder="请输入交接 网点代码"></el-input>
			</div>
    </div>
    <div class="SingleLatitude">
      <div class="SingleLatitudeScan">
        <div>
          <span class="iconfont icon-saomiao" @click="androidScan('labelInput')"></span>
          <input type="text" v-model="labelInput" placeholder="输入要异常上报的运单">
          <span @click="confirmLabelInput">确定</span>
        </div>
      </div>
      <div class="SingleLatitudeBox">
        <div class="SingleLatitudeBox_head">请选择要异常上报的运单</div>
        <div class="SingleLatitudeBox_box">
          <div @click='selectLabel(index)'  v-for='(dataItem,index) in labelList'  :id="index"  :key='index'>
            <span>{{dataItem.productNo}}</span>
            <span class="iconfont icon-weixuanzhong" ></span>
          </div>
        </div>
        <div class="SingleLatitudeBox_btn">
          <span class="checkAll" @click="checkAllLabel">全选</span>
          <span class="UnselectAll" @click="UnselectAllLabel">全不选</span>
        </div>
        <div class="SelectedWaybill" v-if='selectedLabelList.length'>
          <div class="SelectedWaybill_head">已选择的运单</div>
          <div class="SelectedWaybill_box">
            <div v-for='(seleItem,seleidx) in selectedLabelList'  :id="seleidx"  :key='seleidx'>
              <span >{{seleItem}}</span>
              <span @click="deleteLabel(seleidx)" class="iconfont icon-jian"></span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="uploadImg" >
      <v-uploader title="上传图片(限3张)"
        url="/system/app/abnormalUploadImage"
        @onErr ="onErr"
        @onSuccess ="onSuccess"
        :limit="3"
        ref="uploadAb"
        name="file"
        :params="uploadParams"/>
        <span class="sampleText" @click="sampleAppear">图片示例</span>
    </div>
    <div class="footer-commit">
      <div class="commit" @click="commitAbo">提交</div>
    </div>
    <pictureSample v-show='sampleShow' linkNode='yc'></pictureSample>
  </div>
</template>
<script>
  import Scan from '@/components/Scan'
  import pictureSample from '@/components/pictureSample'
  import Header from '@/components/header'
  import Uploader from '@/components/uploader'
  import * as fetchObj from '@/api/index/aBnormal'
  import $ from 'jquery'
  import { iatRecorder } from '@/utils/iatRecorder'
	import Vue from 'vue';
	import { Toast, Dialog } from 'vant';
	Vue.use(Toast).use(Dialog);
  export default {
    name: 'Abnormal',
    components: {
      'v-scan': Scan,
      'v-header': Header,
      'v-uploader': Uploader, // 上传组件
      'pictureSample': pictureSample
    },
    data() {
      return {
        fetchObj,
        headerName: '上报异常',
        responseData: {},
        OMS: {},
        aboType: '', // 异常类型
        typeOptions: [], // 异常类型下拉
        aboReason: '',
        reasonOptions: [],
        recipientContactList: ['寄方', '收方'], // 改派收件联系人选择列表
        reassignRecipientContact: '', // 改派收件联系人
        reassignmentAppointmentTime: this.timestampFormat(new Date().getTime(), 'YYYY-MM-DD'), // 改派预约日期
        appointmentPeriod: '', // 改派预约时间段
        appointmentPeriodList: [], // 改派预约时间段数组
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        localtttOptions:[],
        aboLink: '',
        linkOptions: [],
        aboPer: '',
        perOptions: [],
        aboText: '', // 异常描述
        allData: {}, // 所有异常数据
        dialogImageUrl: '', // 图片路径
        dialogVisible: false, // 是否放大预览图片
        imgUrl: null,
        imgObj: null,
        uploadParams: {}, // 图片上传附带参数
        imageUrl: '',
        switchScan: true,
        uploadSuccessNum: 0, // 上传成功数量
        uploadTotalNum: 0, // 上传图片总数
        uploadFailNum: 0, // 上传失败数量
        shipmentCode: '', // 配载单号
        omsNo: '', // 订单号
        deliveryNoSF: '', // SF运单号
        linkno: '10', // 节点
        CurrentCity: '', // 当前城市
        CurrentLocation: '', // 当前地址
        CurrentDistrict: '', // 当前区县
        longitude: '',
        latitude: '',
        labelList: [], // 标签号列表
        selectedLabelList: [], // 已选择的标签号列表
        labelInput: '', // 手动输入的标签
				iatRecorder3: null,
				mySecond: 0,
				startPerform: false,
        sampleShow: false, // 图片示例是否展示
        sfNetworkNum: '', //  网点人员工号 401107
				projectType: 0, // 订单类型
				sfNetCode: '' // 网点代码
      }
    },
    watch: {
      aboType(val, oval) {
        let that = this;
        if (val != oval) {
          that.aboReason = '';
          for (let ty = 0; ty < that.allData.newAbnormalType.length; ty++) {
            if (that.allData.newAbnormalType[ty].abnormalType == val) {
              that.reasonOptions = that.allData.newAbnormalType[ty].abnormalReason;
            }
          }
        }
      }
    },
    mounted() {
      this.getAboList();
      this.getAppointmentPeriodData();
      let that = this;
      this.queryData(that.omsNo);
      $('.LoadImg_conentul ul.el-upload-list+div').click(function(e){
        event.stopPropagation();
        that.switchScanFun( false); // 关闭摄像头
      })
    },
    created() {
      this.getAboList();
      let that = this;
      if (this.$route.query.shipmentCode) {
        this.shipmentCode = this.$route.query.shipmentCode;
      }
      if (this.$route.query.omsNo) {
        this.omsNo = this.$route.query.omsNo;
        this.OMS.omsNo = that.omsNo;
      }
      if (this.$route.query.deliveryNoSF) {
        this.deliveryNoSF = this.$route.query.deliveryNoSF;
        this.OMS.deliveryNoSF = that.deliveryNoSF;
      } else {
        this.OMS.deliveryNoSF = '';
      }
      if (this.$route.query.linkno) {
        this.linkno = this.$route.query.linkno;
      }
      if (this.$route.query.labelList) {
        this.labelList = this.$route.query.labelList;
        let labelListJsonArr = []
        for (let k = 0;k < that.labelList.length;k++) {
          labelListJsonArr[k]= {
              ifSelect: false,
              productNo: that.labelList[k]
          }
        }
        this.labelList = Object.assign([],labelListJsonArr)
      }
    },
    methods: {
      ScanSFNumber(inputName) {
				window.QRScanAjax = this.QRScanSFNumber;
				window.TellVue_QRScanResult_Ajax = this.QRScanSFNumber;
				this.$store.state.ScanQRCodeInputName = inputName;
				if (!(this.getItem('SXJF_ifScan') && this.getItem('SXJF_ifScan') == '是')) {
					// 安卓
					try {
						CallAndroidOrIOS.VueSCAN();
					}
					catch(error) {}
				}
				// 苹果
				try {
					window.webkit.messageHandlers.messageSend.postMessage({
						a: '调用app原生扫描二维码/条码',
						b: inputName
					})
				} catch (error) {}
			},
			QRScanSFNumber(qrcode) {
				let that = this;
				let inputName = this.$store.state.ScanQRCodeInputName;
				this[inputName] = qrcode;
        this.queryNetCode()
			},
			onSearch(val) {
				if (val != '') {
					if (!this.messageSendflag) {
            this.messageSendflag = true;
            //发送语音消息代码
						this.onIMMessageUpdate(this.onIMGetMessage(this.loginUserName, '', val, 0));
					} else {
					  this.myMessageData[this.myMessageData.length-1].content=val;
					}
				}
			},
      // 接收iOS/android值
      QRScanAjax(qrcode) {
          let that = this;
          let inputName = this.$store.state.ScanQRCodeInputName;
          this[inputName] = qrcode;
          this.confirmLabelInput();
      },
      SetCurrAddress(lngad) {
      	this.ReceivingLatitud(lngad);
      },
      sampleAppear() {
        this.sampleShow = true;
      },
      // 上传图片完成后（包括部分上传失败）
      finishUpload(text) {
        let that = this;
        that.$emit('isLoading', false);
        let textvalue = '';
        if (text) {
          textvalue = text ? ',' + text : '';
        }
        this.$alert('异常上报成功' + textvalue, '提示', {
            confirmButtonText: '确定',
            callback(){
              that.$router.back(-1);
            }
        })
      },
      // 根据小哥工号查询网点代码
			queryNetCode() {
				let that = this;
				if (!this.sfNetworkNum) {
					return
				}
				this.httpRequest1('post', this.fetchObj.getEmpInfo, {
					courierEmpCode: that.sfNetworkNum
				}).then(res => {
					if (res.entity) {
						that.sfNetCode = res.entity.netCode
					} else {
            that.sfNetCode = ''
          }
				}).catch((err) => {
          that.sfNetCode = ''
        })
			},
      /**
       * 提交异常
       */
       commitAbo() {
        let that = this;
        if (!that.selectedLabelList.length) {
          that.$alert('请选择运单号', '提示', {
            confirmButtonText: '确定',
          })
          return
        }
        if (!that.aboType) {
					that.$alert('请选择异常类型', '提示', {
						confirmButtonText: '确定',
					})
					return
				}
				if (!that.aboReason) {
					that.$alert('请选择异常原因', '提示', {
						confirmButtonText: '确定',
					})
					return
				}
        if (this.linkno == '40') {
          this.linkno = '30';
        }
        if (this.projectType == 1 && this.linkno == '30' && this.aboType == '客户类' && (this.aboReason == '寄方客户要求退回' || this.aboReason == '客户要求转寄其它地址')) {
					if (!this.sfNetworkNum || !this.sfNetCode) {
						this.$alert('请输入网点信息', '提示', {
							confirmButtonText: '确定',
						})
						return
					}
				}
        if (this.linkno == '30' && this.aboType == '客户类' && this.aboReason == '经客户同意，更改收派时间') {
          if (!this.reassignmentAppointmentTime || !this.appointmentPeriod || !this.reassignRecipientContact) {
						this.$alert('请输入改派信息', '提示', {
							confirmButtonText: '确定',
						})
						return
					}
        }
        this.uploadParams.omsNo = this.omsNo; // 订单号
        this.uploadParams.fileType = '异常';
        this.uploadParams.labelNo = this.linkno; // 扫描环节
        let abnormalExplain = '';
        if (this.linkno == '30' && this.aboType == '客户类' && this.aboReason == '经客户同意，更改收派时间') {
          abnormalExplain = '改派联系人：' + this.reassignRecipientContact + ';' + this.aboText;
        } else {
          abnormalExplain = this.aboText;
        }
        that.uploadTotalNum = $('div.uploadImg ul>li').length;
        let params = {
          omsNo: this.OMS.omsNo,
          deliveryNoSF: this.OMS.deliveryNoSF,
          transporterId: this.$store.state.userInfo.orgnizationId,
          transporterName: this.$store.state.userInfo.orgnizationName,
          sponsorName: this.$store.state.userInfo.userName,
          cellphone: that.$store.state.userInfo.cellphone, // 司机电话
          abnormalType: this.aboType,
          abnormalReason: this.aboReason,
          abnormalLink: this.linkno,
          responsibleParty: this.aboPer,
          abnormalExplain: abnormalExplain,
          city:that.CurrentCity,
          labelNoArr:that.selectedLabelList,
					courierEmpCode: this.sfNetworkNum,
					netCode: this.sfNetCode,
          projectType: this.projectType,
          extendAttach3: this.reassignmentAppointmentTime + ' ' + this.appointmentPeriod // 改派日期 时间段
        }
        this.httpRequest1('post', this.fetchObj.abnormalAdd, params).then(res => {
          let img1 = that.$refs.uploadAb.getImgNum();
          that.uploadParams.abnormalId  = res.entity ? res.entity.id : 0; // 异常id
          if (img1 > 0) {
            that.$refs.uploadAb.submit(this);
          }
          that.$alert('异常上报成功', '提示', {
            confirmButtonText: '确定',
              callback: action => {
              }
          })
        })
      },
      onSuccess() {
        this.$router.back(-1);
      },
      onErr() {
        this.$router.back(-1);
      },
      // 扫描后
      queryData(data) {
        let that = this;
        this.httpRequest1('post', this.fetchObj.reportAbnormalHomeSelect, {
            labelNo: data
        }).then(res => {
          console.log(res);
            if (res.entity) {
              // 订单大类:1.直客 2.产品 3.整车陆运 4.港到港 5.非港到港 6.落地配 7.丰羿快运
              that.projectType = res.entity.projectType || 0
          }
        })
      },
      // 选择标签
      selectLabel(index) {
        let that = this;
        that.labelList[index].ifSelect = !that.labelList[index].ifSelect;
        let iconElement = $('.SingleLatitudeBox_box>div').eq(index).children('span.iconfont');
        if (iconElement.hasClass('icon-xuanzhong')) {
          that.selectedLabelList = that.selectedLabelList.filter(item => {
            return item !== that.labelList[index].productNo
          })
        	iconElement.removeClass('icon-xuanzhong').addClass('icon-weixuanzhong');
        } else if (iconElement.hasClass('icon-weixuanzhong')) {
          that.selectedLabelList.push(that.labelList[index].productNo);
        	iconElement.removeClass('icon-weixuanzhong').addClass('icon-xuanzhong');
        }
      },
      // 删除已选中运单
      deleteLabel(idx){
        let that = this;
        for (let t = 0;t < that.labelList.length;t++) {
          if (that.labelList[t].productNo == that.selectedLabelList[idx]) {
            that.labelList[t].ifSelect = false;
            that.selectedLabelList.splice(idx,1);
            $('.SingleLatitudeBox_box>div').eq(t).children('span.iconfont').removeClass('icon-xuanzhong').addClass('icon-weixuanzhong')
            break;
          }
        }
      },
      // 确定扫描 或 手动输入的标签
      confirmLabelInput(){
        let that = this;
        that.labelList.forEach(function(item, idx) {
          if (that.labelInput == item.productNo) {
            item.ifSelect = true;
            $('.SingleLatitudeBox_box>div').eq(idx).children('span.iconfont').removeClass('icon-weixuanzhong').addClass('icon-xuanzhong');
            that.selectedLabelList = that.selectedLabelList.filter(items => {
              return items !== item.productNo
            })
            that.selectedLabelList.push(item.productNo);
          }
        })
      },
      // 全选
      checkAllLabel(){
        let that = this;
        that.selectedLabelList = [];
        for (let p = 0;p < that.labelList.length; p++) {
          that.labelList[p].ifSelect = true;
          that.selectedLabelList[p] = that.labelList[p].productNo;
          $('.SingleLatitudeBox_box>div').eq(p).children('span.iconfont').removeClass('icon-weixuanzhong').addClass('icon-xuanzhong')
        }
      },
      // 全不选
      UnselectAllLabel(){
        let that = this;
        for (let p = 0;p < that.labelList.length; p++) {
          that.labelList[p].ifSelect = false;
          $('.SingleLatitudeBox_box>div').eq(p).children('span.iconfont').removeClass('icon-xuanzhong').addClass('icon-weixuanzhong')
        }
        that.selectedLabelList = [];
      },
      // 获取二次派送预约时间段 数据字典
      getAppointmentPeriodData() {
        let that = this;
        let postData = {
          dictionaryNum: "ORDER_RESERVATION_TIME_TYPE"
        };
        this.httpRequest1('post', this.fetchObj.getChildDataDictionaryByParentCode, postData).then(res => {
            that.appointmentPeriodList = res.entity || []
        })
      },
      // 请求下拉框数据
      getAboList() {
        let that = this;
        this.httpRequest1('post', '/system/app/abnormalSeleteData', {}).then(res => {
          that.typeOptions = [] // 异常类型
          that.reasonOptions = [] // 异常原因
          that.linkOptions = [] // 异常环节
          that.perOptions = [] // 责任方
          let obj = res.entity
          that.allData = obj;
          for (let i in obj.abnormalLink) { // 异常环节
            let iitem = obj.abnormalLink[i]
            let iarr = {}
            iarr.value = iitem
            iarr.label = iitem
            that.linkOptions.push(iarr)
          }
          that.typeOptions = obj.newAbnormalType;
          for (let l in obj.responsibleParty) { // 责任方
            let iteml = obj.responsibleParty[l]
            let arrl = {}
            arrl.value = iteml
            arrl.label = iteml
            that.perOptions.push(arrl)
          }
        })
      },
      // 扫描后
      scanData(data) {
				if (data.length < 11) {
					this.$alert('子单不能小于11位数,请重新扫描', '提示', {
					confirmButtonText: '确定'
					})
					return
				}
        let that = this;
        let postData = {
          omsNo: data // 标签号
        };
        this.uploadParams.omsNo = data; // 订单号
        this.httpRequest1('post', '/system/app/queryOrderByOmsNo', postData).then(res => {
          that.OMS = {
            omsNo: res.entity.omsNo,
            deliveryNoSF:res.entity.deliveryNoSF
          }
        })
      },
      goPrev() {
        this.$router.go(-1);
      },
      switchScanFun(data) {
        if (data) {
          this.switchScan = true // 打开摄像头
        } else {
          this.switchScan = false // 关闭摄像头
        }
      }
    }
  }
</script>
<style scoped lang="less">
  @import "../../../components/publicLess.less";
  .Abnormal{
    font-size: 28/50rem;
  }
  .form-content{
    padding: 20px;
    background-color: #fff;
    position: relative;
  }
  .form-item {
    margin: 30/50rem 0;
    .icon-yuyin{
			margin-left: 20/50rem;
			color: @PublicColor;
		}
		.form-prompt{
			color: #999;
			font-size: 27/50rem;
		}
		.form-end{
			float: right;
		}
    &>div{
      margin-top: 15/50rem;
    }
  }
  .form-item label {
    display: inline-block;
    font-size: 16px;
    color: #6f7180;
  }
  .form-item .sf-network-num{
		display: flex;
		line-height: 70/50rem;
		input{
			flex-grow: 1;
		}
		i{
			font-size: 50/50rem;
			color: @PublicColor;
			margin: 0 20/50rem;
		}
		span{
			height: 60/50rem;
			margin-top: 5/50rem;
			line-height: 60/50rem;
			width: 180/50rem;
			font-size: 28/50rem;
			background-color: @PublicColor;
			text-align: center;
			color: #fff;
			border-radius: 8/50rem;

		}
	}
  .footer-commit{
    font-size: 28/50rem;
    text-align: center;
    display: flex;
    width: 100%;
    color: #fff;
  }
  .footer-commit .commit{
    flex: 1;
    line-height: 70/50rem;
    margin: 0 30/50rem 30/50rem;
    background-color: @PublicColor;
    text-align: center;
    border-radius: 35/50rem;
  }
  .uploadImg{
    padding:0 30/50rem 30/50rem;
    margin-bottom: 15/50rem;
    box-sizing:border-box;
    div{
      float: none;
    }
    span{
      float: none;
    }
    .myUpload{
      padding-bottom: 0;
    }
  }
  .kong{
    width: 100%;
    height: 70/50rem;
  }
</style>